<!--  -->
<template>
  <div class="cover-container"
       @click="showCoverSelect">
    <div class="cover-wrap">
      <img class="cover-img"
           ref="cover-image"
           :src="imageVal">
    </div>
    <!-- <div>{{imageVal}}</div> -->
    <!-- <div>{{value}}</div> -->
    <el-dialog title="选择封面"
               :visible.sync="dialogVisible"
               width="60%"
               append-to-body>
      <el-tabs v-model="activeName"
               type="card">
        <el-tab-pane label="素材库"
                     name="first">
          <!-- 素材列表   -->
          <image-list :isShowUpload="false"
                      ref="image-list" />
        </el-tab-pane>
        <!-- 上传图片 -->
        <el-tab-pane label="上传图片"
                     name="second">
          <input type="file"
                 ref="file"
                 @change="fileChange">
          <img src=""
               width="100"
               alt=""
               ref="preview-image">
        </el-tab-pane>
      </el-tabs>
      <span slot="footer"
            class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary"
                   @click="onCoverConfirm">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { uploadImages } from '@/api/images'
import ImageList from '@/views/image/components/image-list'
import readFileImg from '@/utils/image-compress' // 图片压缩
export default {
  name: 'UploadCover',
  components: {
    ImageList
  },
  // props: ['cover-image'],
  props: ['value'],
  data () {
    return {
      baseURL: this.baseURL,
      dialogVisible: false,
      activeName: 'first',
      maxSize: 500, // 限制图片最大为500kb
      imgSrc: '',
      formData: '',
      imageVal: ''
    }
  },
  computed: {},
  beforeMount () {
    this.imageVal = this.value ? (this.baseURL + '/uploads/' + this.value) : ''
  },
  beforeUpdate () {
    // this.imageVal = this.value ? (this.baseURL + '/uploads/' + this.value) : ''
  },
  watch: {
    value (newVal, oldVal) {
      // console.log(newVal)
      // console.log(oldVal)
      this.imageVal = this.value ? (this.baseURL + '/uploads/' + this.value) : ''
    }
  },
  created () { },
  mounted () { },
  methods: {
    showCoverSelect () {
      this.dialogVisible = true
    },
    fileChange () {
      const file = this.$refs.file.files[0]
      const blob = window.URL.createObjectURL(file)
      this.$refs['preview-image'].src = blob
      // 防止用户选择同一个文件不触发事件
      // this.$refs.file.value = ''
    },
    // readFileImg (file, resolve, reject) {
    //   // 读取图片信息并展示
    //   const reader = new FileReader() // 读取文件实例
    //   reader.readAsDataURL(file) // 将文件读取为 DataURL
    //   reader.onload = () => { // 文件读取成功完成时触发
    //     const img = new Image()
    //     img.src = reader.result // 文件一旦开始读取，无论成功或失败，实例的 result 属性都会被填充。如果读取失败，则 result 的值为 null ，否则即是读取的结果，绝大多数的程序都会在成功读取文件的时候，抓取这个值。
    //     img.onload = () => {
    //       // this.imgSrc = img.src // 以上是将选择的图片展示出来
    //       const originWidth = img.naturalWidth // 获取图片原始大小
    //       const originHeight = img.naturalHeight
    //       const originSize = file.size / 1024 // 计算图片多少kb
    //       this.compressEvent(file, img, originSize, originWidth, originHeight, resolve, reject)
    //     }
    //   }
    //   reader.onerror = function (error) {
    //     console.log(`error: ${error}`)
    //   }
    // },
    // compressEvent (file, img, originSize, originWidth, originHeight, resolve, reject) {
    //   // 将图片绘制到canvas上进行压缩
    //   const canvas = document.createElement('canvas')
    //   const context = canvas.getContext('2d')
    //   const maxSize = this.maxSize
    //   if (originSize <= maxSize) {
    //     const fd = new FormData()
    //     fd.append('image', file)
    //     this.formData = fd
    //     resolve(fd)
    //     return false
    //   }
    //   const mul = originSize / maxSize
    //   const targetWidth = originWidth / mul
    //   const targetHeight = originHeight / mul
    //   canvas.width = targetWidth
    //   canvas.height = targetHeight
    //   context.clearRect(0, 0, targetWidth, targetHeight) // 清除画布
    //   context.drawImage(img, 0, 0, targetWidth, targetHeight) // 画图

    //   const dataURL = canvas.toDataURL('image/jpeg', 0.1) // 将其转化成base64字符串

    //   const files = this.dataURLtoFile(dataURL, 'image/jpeg') // 将base64转换为file文件

    //   const fd = new FormData()
    //   fd.append('image', files)
    //   this.formData = fd
    //   resolve(fd)
    // },
    // dataURLtoFile (dataurl, filename) {
    //   // 将base64转换为file文件
    //   const arr = dataurl.split(',')
    //   const mime = arr[0].match(/:(.*?);/)[1]
    //   const bstr = atob(arr[1])
    //   let n = bstr.length
    //   const u8arr = new Uint8Array(n)
    //   while (n--) {
    //     u8arr[n] = bstr.charCodeAt(n)
    //   }
    //   return new File([u8arr], filename, { type: mime })
    // },

    async onCoverConfirm () {
      if (this.activeName === 'second') {
        const file = this.$refs.file.files[0]
        if (!file) {
          this.$message('请选择文件')
          return
        }
        const fd = await new Promise((resolve, reject) => {
          readFileImg(file, resolve, reject)
        })

        uploadImages(fd).then(res => {
          // 关闭弹出层
          this.dialogVisible = false
          // 展示上传的图片
          // this.$refs['cover-image'].src = `http://1.15.144.141:8081${res.data.url}`
          this.$refs['cover-image'].src = `${this.baseURL}${res.data.data.url}`

          // 将图片地址发送给父组件
          // this.$emit('input', `http://1.15.144.141:8081${res.data.url}`)
          // console.log(`${this.baseURL}${res.data.data.url}`)
          this.$emit('input', `${res.data.data.url}`)
          // this.$emit('updata-cover', res.data.data.url)
        })
      } else if (this.activeName === 'first') {
        // 获取子组件的数据dom
        const imageList = this.$refs['image-list']
        const selected = imageList.selected
        if (selected === null) {
          this.$message('请选择封面图片')
        }

        this.dialogVisible = false
        // 提交给父组件
        // this.$emit('input', 'http://1.15.144.141:8081/uploads/' + imageList.images[selected].img)
        this.$refs['cover-image'].src = `${this.baseURL}/uploads/${imageList.images[selected].img}`
        // console.log(this.baseURL + '/uploads/' + imageList.images[selected].img)
        this.$emit('input', imageList.images[selected].img)
        // console.log(imageList.images[selected].img)
      }
    }
  }
}
</script>

<style lang='less' scoped>
.cover-container {
  width: 150px;
  margin-right: 10px;
}
.cover-wrap {
  width: 150px;
  height: 120px;
  overflow: hidden;
  border: 2px solid #a7a7a7;
  cursor: pointer;
  background: url(../../../assets/tips.png);
  background-size: 100%;
  .cover-img {
    position: relative;
    left: 50%;
    top: 50%;
    transform: translate(-50%, -50%);
    max-width: 100%;
    max-height: 100%;
  }
}
</style>
